<?php
/**
 * 回收站管理
 * @author huanran.zhao
 * 2014/4/20
 */
class RecycleApp extends CommonApp {
	
	/**
	 * 数据列表
	 */
	public function indexAct(){
		$where = '1 ';
		if(My::is_var(My::arr2var($_GET,'table')))
			$where .= "AND `table`='".$_GET['table']."' ";
		if(My::arr2var($_GET,'author')!='')
			$where .= "AND `author`='".I('get.author')."' ";
		if(My::is_date(My::arr2var($_GET,'adddate')))
			$where .= "AND `adddate` like '".$_GET['adddate']."%' ";
		$page = My::page(DB('recycle')->where($where)->cache()->count());
		$result = DB('recycle')->where($where)->cache()->limit($page['limits'])->order("adddate DESC")->select();
		if($result)
		foreach($result as &$value){
			$value['data'] = My::decodeJson($value['data']);
		}
		$this->assign('result',$result);
		$this->assign('page',$page);
		//数据表 group
		$tables = DB('recycle')->field('`table`')->group('`table`')->select();
		$this->assign('tables',My::arr2one($tables,'table'));
		//print_r($result);
		$this->display();
	}

	/**
	 * 撤销恢复数据
	 */
	public function undoAct(){
		$id = My::arr2var($_GET,'id');
		if(!My::is_id($id))
			$this->ajaxReturn(300,'ID错误');
		$result = DB('recycle')->where("id={$id}")->find();
		if(!$result)
			$this->ajaxReturn(300,'数据不存在');
		$has = DB($result['table'])->where("id={$result['idid']}")->count();
		//原表中已存在该id的数据,则新增一条
		if($has){

		}
		//还原
		else{
			$data = My::decodeJson($result['data']);
			$ok = DB($result['table'])->clear()->add($data);
			if($ok){
				//删除recycle表中的记录
				DB('recycle')->where("id={$id}")->clear()->delete();
				$this->ajaxReturn(200,'数据恢复成功!');
			}
			else
				$this->ajaxReturn(200,'数据恢复失败!');
		}
	}

	public function deleteAct(){
		$check_id = My::arr2var($_POST,'check_id');
		if(!$check_id)
			$this->ajaxReturn(300,'请选择数据!');
		$check_id = My::implode(',',$check_id);
		if(!$check_id)
			$this->ajaxReturn(300,'数据错误!');
		if(!My::is_string($check_id, 'n', ','))//ids只能数字和逗号
		    My::ajaxReturn(300,'参数错误!');
		$ok = DB('recycle')->where("id IN($check_id)")->clear()->delete();
		if($ok)
			$this->ajaxReturn(200,'删除成功!');
		else
			$this->ajaxReturn(200,'删除失败!');
	}

}